<?php
namespace Beerus\Modules\DesignerAuth\Controllers;

use App\Http\Controllers\Controller;
use Biz\pockets\excel\DownExcel;
use Doraemon\model\Designer\DesignerOpLog;
use Doraemon\model\Member;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class AuditLogController extends Controller
{
	public function __construct()
	{
		parent::__construct();
		Admin::script('$(".pjax-container").attr("id","pjax-container");');
	}

	public function export(Request $request)
	{
		$params = $request->all();

		$condition = [];
		if (isset($params['uid'])) {
			$condition['uid'] = $params['uid'];
		}

		if (isset($params['op'])) {
			$condition['op'] = $params['op'];
		}

		if (!empty($params['op_time']['>='])) {
			$condition['op_time[>=]'] = $params['op_time']['>='];
		}

		if (!empty($params['op_time']['<='])) {
			$condition['op_time[<=]'] = $params['op_time']['<='];
		}

		$condition['ORDER'] = [
			'op_time' => 'DESC'
		];

		$lists = DesignerOpLog::select('*', $condition);

		if (empty($lists)) {
			$error = new MessageBag([
				'title' => '暂无数据可导出'
			]);

			return back()->with(compact('error'));
		}

		$user_ids = array_column($lists, 'uid');
		$member_info = Member::getUsers($user_ids);

		$data = [];
		foreach ($lists as $item) {
			$row = [
				'uid' => $item['uid'],
				'nick' => empty($member_info[$item['uid']]['nick']) ? '' : $member_info[$item['uid']]['nick'],
				'op' => DesignerOpLog::OP_DESC[$item['op']],
				'reason' => $item['reason'],
				'op_time' => $item['op_time'],
				'admin_name' => $item['admin_name'],
			];
			$data[] = $row;
		}

		// 设置列宽
		$letter = range('A', 'F');
		$header = [
			'UID', '昵称', '操作', '原因', '操作时间', '操作人'
		];

		$excel = new DownExcel();
		$excel->setFileName('设计师审核操作记录 - ' . date('YmdHis'));
		$excel->setSheetTitle('设计师审核操作记录');

		// 设置列宽
		$width = [
			'A' => 15,
			'B' => 20,
			'C' => 15,
			'D' => 45,
			'E' => 20,
			'F' => 15,
		];

		$excel->setWidth($width);
		$excel->setDefaultStyleAlignment();

		foreach ($header as $key => $value) {
			// 设置字体
			$excel->setFrontName($letter[$key]);
			// 设置加粗
			$excel->setFrontBold("$letter[$key]1");
			// 设置大小
			$excel->setFrontSize($letter[$key]);
		}

		$excel->create($data, $header);
	}
}
